
var dataSource = new Array();
//table的数据源
var table; //table对象
dataSource = [];

function setCheckBoxs() {
    var isChecked = $("#integralAllUnder")[0].checked ;
    $("#integralAll")[0].checked = isChecked;
    if(isChecked){
        $('#deleteSelected').removeAttr("href");
        $('#deleteSelected').removeAttr("style");
    }else {
        $('#deleteSelected').attr('href',"javascript:return false;");
        $('#deleteSelected').attr('style',"opacity: 0.2");
    }

	var checkBoxValues = $("#datatable").find("tbody").find("input[type=checkbox]") ;
	if (checkBoxValues && checkBoxValues.length>0){
        for (var i=0;i<checkBoxValues.length;i++){
            checkBoxValues[i].checked = isChecked ;
		}
	}
}
function deleteSelected() {
    var checkBoxValues = $("#datatable").find("tbody").find("input[type=checkbox]:checked") ;

    if (checkBoxValues && checkBoxValues.length>0){
        var ids = checkBoxValues[0].value;
        for (var i=1;i<checkBoxValues.length;i++){
        	if (checkBoxValues[i]){
                ids += ","+checkBoxValues[i].value ;
			}
        }
        integralSkuDelete(null,ids) ;

    }
}
function goodsList(data) {
	if(dataSource.length>0){
	dataSource.splice(0, dataSource.length); //清空数组
    }
if(data.data.data!=null){
	$.each(data.data.data, function(i, field) {
		var rowData = new Array();
		rowData.push(field.integralSkuCode);
        rowData.push(field.integralSkuName);
        rowData.push(field.unitName);
        rowData.push(field.integralSkuImgs != null && field.integralSkuImgs[0]!=null ? field.integralSkuImgs[0].imgUrl : "");
        rowData.push(field.creationDate);
        rowData.push(field.lastModifiedDate);
        rowData.push(field.creationBy);
		rowData.push(field.integralSkuId);

		dataSource.push(rowData);
	});
}

	initDataTable(dataSource);

	function initDataTable(dataSource) {
		var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
		dttable.fnClearTable(); //清空一下table
		dttable.fnDestroy(); //还原初始化了的datatable
		$("#datatable").DataTable({
			"autoWidth": false,
			"ordering": false,
			"searching": false,
			"paging": false,
			"retrieve": true,
			"destroy": true,
			"bAutoWidth": true,
			"bLengthChange": true,
			"aLengthMenu": [50, 25, 10, 5],
			"oLanguage": {
				"sLengthMenu": "每页显示 _MENU_ 条记录",
				"sZeroRecords": "抱歉， 没有找到",
				"sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
				"sInfoEmpty": "没有数据",
				"sInfoFiltered": "(从 _MAX_ 条数据中检索)",
				"oPaginate": {
					"sFirst": "首页",
					"sPrevious": "前一页",
					"sNext": "后一页",
					"sLast": "尾页"
				},
				"sZeroRecords": "没有检索到数据",
				"sProcessing": "<img src='./loading.gif' />"
			},
			data: dataSource,
			columnDefs: [{
					"visible": true,
					"targets": 0
				},
				{
					"render": function(data, type, row, meta) {
                        var val = '<span><td><input class="spuId" type="checkbox" onclick="checkItem()"  name="integralSkuId" value = "' + row[0] + '">' + row[0] + '</td></span>';
						return val;
					},
					"targets": 0
				},
				{
					"render": function(data, type, row, meta) {
                        var val = '<a><span class="list 84" onclick="integralSkuDelete(\'\',' + row[0] + ')">删除</span></a>&nbsp;&nbsp;' +
                            '<a><span class="list 84" onclick="integral_edit(\'积分商品详情\',\'integralSkuInfo.html\',' + row[0] + ')">编辑</span></a>' ;
                        return val;
                    },
                    "targets": 7
				},
                {
                    "render": function(data, type, row, meta) {
                        if(row[3] != '') {
                            var val = '<span id="integralImg1" ><img onclick="picShow(\'查看图片\',\'picShow.html\',\''+row[3]+'\')" src="'+row[3]+'" width="100" height="100"></span>';
                            return val;
                        }else {
                            var val = '<span></span>';
                            return val;
                        }
                    },
                    "targets": 3
                }
			]
		});
		//权限控制函数
        power()
	};
}


//删除
function integralSkuDelete(val,id) {
    var curInd = layer.confirm(
        '<span>确定要删除该积分商品吗？</span>'+'<br/>', {title:'积分商品',btn: ['确定', '取消']}, function(index){
            layer.close(curInd);
            doIntegralSkuDelete(id)

        },function(){
            layer.close(curInd);

        });

}
function doIntegralSkuDelete(id) {
    $.ajax({
        url:root.goodsInter.goods_deleteIntegralSku,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "ids":id,
        }),
        success: function (data) {
            if(data.errorCode==0){
                $.Huimodalalert('删除成功！',2000);
                goodsDistributionMode()
            }else {
                showMsg(5, data.msg);
            }
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
    layer.close(index);
}

//弹框
function showMsg(icon, msg) {
    layer.msg(msg, {
        icon: icon,
        time: 3000
    });
}
/*表单验证特殊字符*/
function ValidateValue(textbox) {
	var IllegalString = "[`~!#$^&*()=|{}':;',\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？]‘’";
	var textboxvalue = textbox.value;
	var index = textboxvalue.length - 1;
	var s = textbox.value.charAt(index);
	if(IllegalString.indexOf(s) >= 0) {
		s = textboxvalue.substring(0, index);
		textbox.value = s;
		layer.msg("不能输入特殊字符");
	}
}


/*账户信息编辑*/
function integral_edit(title, url, row) {
	sessionStorage.setItem('integralSkuCode', row)
	var index = layer.open({
		type: 2,
		title: title,
		content: url
	});
	layer.full(index);
}

function goodsDistributionMode() {

	$.ajax({
		contentType: 'application/json',
		url: root.goodsInter.goods_integral_sku_list,
		cache: false, //禁用缓存
		type: "POST",
		data: JSON.stringify({
			pageSize: 50,
			nowPage: 1,
			model: {
                integralSkuName: $("#integralSkuName").val(),
                integralSkuCode:$("#integralSkuCode").val(),
                creationBy:$("#creationBy").val(),
                creationDateStart:$("#timemin").val(),
                creationDateEnd:$("#timemax").val()
			} //传入组装的参数
		}),
		success: function(data) {
			goodsList(data);
			$("#integralAll").attr("checked", false);
			$("#checkboxs").css({
				display: "inline"
			});

			totalPage = data.data.pageCount;
			$('.M-box3').pagination({
				pageCount: totalPage,
				jump: true,
				coping: true,
				prevContent: '上页',
				nextContent: '下页',
				callback: function(api) {
					console.log(api.getCurrent());
					$.ajax({
						contentType: 'application/json',
						url: root.goodsInter.goods_integral_sku_list,
                        // url: "http://localhost:8080/product/product/spuList",
						cache: false, //禁用缓存
						type: "POST",
						data: JSON.stringify({
							pageSize: 50,
							nowPage: api.getCurrent(),
							model: {
                                integralSkuName: $("#integralSkuName").val(),
                                integralSkuCode:$("#integralSkuCode").val(),
                                creationBy:$("#creationBy").val(),
                                creationDateStart:$("#timemin").val(),
                                creationDateEnd:$("#timemax").val()
							} //传入组装的参数
						}),
						success: function(data) {
							goodsList(data);
                            $("#integralAll").attr("checked", false);
						}
					});
				}
			});
		}
	});
}
//获取用户信息
var localStorageParameters = decodeURIComponent(web.readCookie("loginData"));
var JsonObject =JSON.parse(localStorageParameters);
function stopProp() {
	var isChecked = $("#integralAll")[0].checked ;
	$("#integralAllUnder")[0].checked = isChecked;
    if(isChecked){
        $('#deleteSelected').removeAttr("href");
        $('#deleteSelected').removeAttr("style");
    }else {
        $('#deleteSelected').attr('href',"javascript:return false;");
        $('#deleteSelected').attr('style',"opacity: 0.2");
    }
	window.event ? window.event.cancelBubble = true : e.stopPropagation();
}

function checkItem() {
    var checkBoxValues = $("#datatable").find("tbody").find("input[type=checkbox]") ;
    if (checkBoxValues && checkBoxValues.length>0){
    	var len = 0 ;
    	for (var i=0;i<checkBoxValues.length;i++){
    		if(checkBoxValues[i].checked){
    			len++ ;
			}
		}
		if (len > 0){
            $('#deleteSelected').removeAttr("href");
            $('#deleteSelected').removeAttr("style");

            var isChecked = len == checkBoxValues.length ;
			$("#integralAll")[0].checked = isChecked;
			$("#integralAllUnder")[0].checked = isChecked;
		}else {
            $("#integralAll")[0].checked = false;
            $("#integralAllUnder")[0].checked = false;

            $('#deleteSelected').attr('href',"javascript:return false;");
            $('#deleteSelected').attr('style',"opacity: 0.2");
		}
    }else {
        $('#deleteSelected').attr('href',"javascript:return false;");
        $('#deleteSelected').attr('style',"opacity: 0.2");
    }

}

var totalPage = 1;

function picShow(title, url, imgUrl) {
	window.event ? window.event.cancelBubble = true : e.stopPropagation();
	sessionStorage.setItem("imgUrl", imgUrl);
	layer_show(title, url, "800", "500");
}